const passport = require('koa-passport')
const LocalStrategy = require('passport-local').Strategy
const User = require('@root/models/user.model')

passport.use(
    new LocalStrategy(
        {
            usernameField: 'user[email]',
            passwordField: 'user[password]',
            session: false
        },
        async (email, password, done) => {
            try {
                const user = await User.findOne({ 'local.email': email });


                console.log('init user---', user)

                if (!user || !user.validPassword(password)) {
                    return done(null, false, {
                        errors: { 'email or password': 'is invalid' }
                    });
                }

                return done(null, user);
            } catch (err) {
                return done(err);
            }
        }
    ))

passport.serializeUser((user, done) => {
    done(null, user)
})

passport.deserializeUser((user, done) => {
    done(null, user)
})

module.exports = passport